package com.UnionPayCenter.task;

import com.UnionPayCenter.account.entity.ChargeBill;
import com.UnionPayCenter.account.entity.FundsBill;
import com.UnionPayCenter.account.enums.ChargeStatusEnum;
import com.UnionPayCenter.account.enums.PayStatusEnum;
import com.UnionPayCenter.account.manager.ChargeBillManager;
import com.UnionPayCenter.account.service.FundsBillService;
import com.UnionPayCenter.task.support.Task;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;

//@Component
@Slf4j
//@Task(initialDelay = 1)
public class ChargeBillTask implements Runnable {

    @Autowired
    private ChargeBillManager chargeBillService;

    @Autowired
    private FundsBillService fundsBillService;


    @Override
    public void run() {
        int page = 1;
        int pageSize = 20;
        log.info("start task: ChargeBillTask");
        int bills = 0;
        while (true) {
            ChargeBill chargeBillDTO = new ChargeBill();
            chargeBillDTO.setState(ChargeStatusEnum.CHARGEING);
            Page<ChargeBill> chargeBills = chargeBillService.getChargeBillByCondition(chargeBillDTO, page, pageSize);
            if (CollectionUtils.isEmpty(chargeBills)) {
                break;
            }
            bills += chargeBills.size();

            for (ChargeBill chargeBill : chargeBills) {
                Date date = chargeBill.getCreateTime();
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE, -4);
                // update charge bill status
                if (date.before(calendar.getTime())) {
                    chargeBillService.updateState(chargeBill.getSn(), ChargeStatusEnum.FAIL);
                    FundsBill fundsBill = new FundsBill();
                    fundsBill.setState(PayStatusEnum.FAIL);
                    fundsBill.setSn(chargeBill.getSn());
                    fundsBillService.updateFundsBill(fundsBill);
                }
                //JSONObject jsonObject = ChinaUmsUtil.search(chargeBill.getThirdSn(), null, null);
                //if ("TRADE_SUCESS".equals(jsonObject.getString("status"))) {
                //    // TODO change to batch
                //    chargeBillService.updateState(chargeBill.getSn(), ChargeStatusEnum.SUCCESS);
                //}
            }
            page += 1;
        }
        log.info("finish task: ChargeBillTask, process bill {}", bills);
    }
}





